#!/usr/bin/perl

##++ updtimages.pl Renames images be all uppercase and then 
##   and then resizes images in one directory and stores
##   the results in another directory.
##--

sub ucase {
  my $SROOT = $_[0];
  my $SDIR = $_[1];

  print "Ucase " . " " . $SDIR . "\n";

  chdir($SROOT . $SDIR) or die "Could not change to " . $SROOT . $SDIR . ".\n";
  foreach my $Name(glob("*")) {
    my $NewName = $Name;
    $NewName =~ s/\s/-/g;
    $NewName =~ s/\(//g;
    $NewName =~ s/\)//g;
    my $FULLNAME = $SROOT . $SDIR . '/' . $Name;
    if(-d $FULLNAME) {
       ucase($SROOT, $SDIR . '/' . $Name);
    }
    else {
##       print "Not a directory " . $Name . ".\n";
       if( $Name =~ m/[a-z ()]/ ) {
          print "Some lowercase, space, or parentheses " . $Name . ".\n";
          rename($FULLNAME,
                  uc($NewName))
                  or die "Could not rename " . $FULLNAME . " to " . $NewName . "\n";
          print "Renamed " . $Name . " to " . uc($NewName) . " in " . $SDIR . ".\n";
       }
       else {
##          print "No lowercase or space " . $Name . ".\n";
       }
    }
  }
}

sub scale {

  my $SROOT = $_[0];
  my $SBIGDIR = $_[1];
  my $SSMALLDIR = $_[2];
  my $SMAXDIM = $_[3];

  print "Scale " . $SBIGDIR . " " . $SSMALLDIR . " " . $SMAXDIM . "\n";
##  print "Chdir " . $SROOT . $SBIGDIR . "\n";
  chdir($SROOT . $SBIGDIR);
  foreach my $Name(glob("*")) {
##    print "Item: " . $Name . "\n";
    my $FULLBIG = $SROOT . $SBIGDIR . '/' . $Name;
    my $FULLSMALL  = $SROOT . $SSMALLDIR . '/' . $Name;
    if(-d $FULLBIG) {
       if(not (-e $FULLSMALL)) { mkdir $FULLSMALL };
       scale($SROOT, $SBIGDIR . '/' . $Name, $SSMALLDIR . '/' . $Name, $SMAXDIM);
    }
    elsif((-e $FULLBIG) and ($Name =~ m/.JPG$/) and (not(-e $FULLSMALL) or ((-M $FULLSMALL) > (-M $FULLBIG)))) {
      my $COMMAND = 'convert -size ' . $SMAXDIM . 'x' . $SMAXDIM . ' ' .
                 $FULLBIG . ' -resize ' . $SMAXDIM . 'x' . $SMAXDIM .
                 ' +profile "*" ' . $FULLSMALL;
      system($COMMAND);
      print "Resizing " . $Name . " from  " . $SBIGDIR . " to " . $SSMALLDIR;
      print " size " . $SMAXDIM . " pixels";
      print "\n";
    }
  }
}

$ROOT=shift;
#'/usr/local/apache-tomcat-5.5.20/webapps/ROOT/';

##print "Running from " . $ROOT . "\n";

&ucase($ROOT, "oversize");
&scale($ROOT, "oversize", "images", "640");
&ucase($ROOT, "images");
&scale($ROOT, "images", "thumbs", "100");
&ucase($ROOT, "thumbs");

exit(0);

